//
//  OrderEditCtrl.m
//  Traveling
//
//  Created by Northwan on 15/6/11.
//  Copyright (c) 2015年 长沙市岳麓区立早网络科技有限公司. All rights reserved.
//  订单填写

#import "OrderEditCtrl.h"
#import "TravelLineOrderEditHeader.h"
#import "TravelLineOrderEditFooter.h"
#import "HotelStayOrderEditHeader.h"
#import "HotelStayOrderEditFooter.h"
#import "MineDataTool.h"
#import "IPNPreSignMessageUtil.h"
#import "IpaynowPluginApi.h"
#import "AFHTTPRequestOperationManager.h"


#define kVCTitle          @"支付测试"
#define kBtnFirstTitle    @"获取订单，开始支付"
#define kWaiting          @"正在获取订单,请稍候..."
#define kNote             @"提示"
#define kConfirm          @"确定"
#define kErrorNet         @"网络错误"
#define kResult           @"支付结果："


@interface OrderEditCtrl ()<UIScrollViewDelegate,UIAlertViewDelegate,IpaynowPluginDelegate,UITextFieldDelegate>
{
    HotelStayOrderEditHeader *_hotelHeaderView;
    HotelStayOrderEditFooter *_hotelFooterView;
    TravelLineOrderEditHeader *_travelHeaderView;
    TravelLineOrderEditFooter *_travelFooterView;
    NSString *_presignStr;
    UIAlertView* mAlert;
    NSMutableData* mData;
}
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)HomeItemDetailHeaderModel *result;
@property(nonatomic,assign)OrderEditCtrlSourceType type;
@property (nonatomic,weak)UIView *currentEditView;
@property (nonatomic,assign)CGFloat moveDis;//移动距离
@property (nonatomic,assign)CGFloat keyboardHeight;//键盘高度，如果为0，代表当前不是编辑模式
@end

@implementation OrderEditCtrl
-(instancetype)initWithData:(HomeItemDetailHeaderModel *)result type:(OrderEditCtrlSourceType)type{
    self = [super init];
    if(self){
        self = [[OrderEditCtrl alloc]init];
        self.result = result;
        self.type = type;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"订单填写"];
     self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH-64)];
    [self.scrollView setDelegate:self];
    [self.scrollView setAlwaysBounceVertical:YES];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionTap)];
    [self.scrollView addGestureRecognizer:tap];
    [self.view addSubview:self.scrollView];
    [self registNotice];
    [self dealWithSourceShow];
}

-(void)registNotice{
    //注册软键盘弹出隐藏的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (BOOL)textFieldShouldBeginEditing:(UITextView *)textView{
    self.currentEditView = textView;
    if (self.keyboardHeight!=0) {
        [self adjustLocationWithKeyboardHeight:self.keyboardHeight];
    }
    return YES;
}
-(void)actionTap{
    [self.view endEditing:YES];
}
-(void)adjustLocationWithKeyboardHeight:(CGFloat)keyboardHeight{
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    CGRect editViewRect = [self.currentEditView convertRect:self.currentEditView.bounds toView:window];
    
    //首页判断键盘有没有遮挡view，如果没有遮挡，那个什么也不做
    CGFloat viewMaxY = CGRectGetMaxY(editViewRect);
    if (viewMaxY+10>SCREENH-keyboardHeight) {
        //代表键盘遮挡了view
        //需要调整uiscrollview的contentoffset移动
        self.moveDis = (viewMaxY+10)-(SCREENH-keyboardHeight);
        [UIView animateWithDuration:0.25 animations:^{
            [self.scrollView setContentOffset:CGPointMake(0, self.scrollView.contentOffset.y+self.moveDis)];
        }];
    }
}

- (void)keyboardWillShow:(NSNotification *)notif
{
    //在键盘显示的时候去调整view
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    
    self.keyboardHeight = keyboardSize.height;
    [self adjustLocationWithKeyboardHeight:keyboardSize.height];
}

-(void)keyboardWillHide:(NSNotification*)notif{
    self.keyboardHeight = 0;
    self.currentEditView = nil;
    if (self.scrollView.contentOffset.y!=0) {
        [self.scrollView setContentOffset:CGPointMake(0, self.scrollView.contentOffset.y-self.moveDis)];
    }
    self.moveDis = 0;
}

-(void)dealWithSourceShow{
    switch (self.type) {
        case HotelStayOrderEditType://酒店住宿
        {
            _hotelHeaderView  = [HotelStayOrderEditHeader initHeaderView];
            [_hotelHeaderView setWidth:SCREENW];
            [_hotelHeaderView initData:self.result];
            [self.scrollView addSubview:_hotelHeaderView];
            
            _hotelFooterView = [HotelStayOrderEditFooter initFooterView];
            _hotelFooterView.firstTitleLabel.text = @"房　间　数：";
            __block OrderEditCtrl *crtl  = self;
            [_hotelFooterView setOperation:^{
                [crtl saveOrder];
            }];
            
            [_hotelFooterView.comeinNameLabel setDelegate:self];
            [_hotelFooterView.nameLabel setDelegate:self];
            [_hotelFooterView.phoneLabel setDelegate:self];
            
            [_hotelFooterView initData:self.result];
            [_hotelFooterView setY:CGRectGetMaxY(_hotelHeaderView.frame)];
            [self.scrollView addSubview:_hotelFooterView];
            [self.scrollView setContentSize:CGSizeMake(0, CGRectGetMaxY(_hotelFooterView.frame))];
            break;
        }
        case TravelLineOrderEditType://旅游线路
        case TravelSpecialtyOrderEditType://旅游特产
        case ScenicoOrderEditType://景点景区
         {
             _travelHeaderView = [TravelLineOrderEditHeader initHeaderView];
             [_travelHeaderView setWidth:SCREENW];
             [_travelHeaderView initData:self.result];
             [self.scrollView addSubview:_travelHeaderView];
             
             _travelFooterView = [TravelLineOrderEditFooter initFooterView];
             __block OrderEditCtrl *crtl  = self;
             [_travelFooterView setOperation:^{
                 [crtl saveOrder];
             }];
             
             [_travelFooterView.nameLabel setDelegate:self];
             [_travelFooterView.phoneLabel setDelegate:self];
             
             [_travelFooterView initData:self.result];
             [_travelFooterView setWidth:SCREENW];
             [_travelFooterView setY:CGRectGetMaxY(_travelHeaderView.frame)-30];
             [self.scrollView addSubview:_travelFooterView];
             [self.scrollView setContentSize:CGSizeMake(0, CGRectGetMaxY(_travelFooterView.frame))];
             break;
         }
        default:
            break;
    }
}

-(void)saveOrder{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *uid =  [DefaultsHelper stringForKey:kUserId];
    [params setObject:uid forKey:@"user_id"];
    [params setObject:@(self.result.contentId) forKey:@"content_id"];
    if(self.result.type == TravelLineDetailType | self.result.type == TravelSpecialtyDetailType | self.result.type ==ScenicoDetailType){//商品类型。可选类型：1、酒店，2、景点景区，3线路，4、旅游特产
        NSInteger prenum = _travelFooterView.countLabel.text.integerValue;
        [params setObject:[NSNumber numberWithInteger:prenum] forKey:@"prenum"];
        NSString *username =  _travelFooterView.nameLabel.text;
        if (_hotelFooterView) {
            username = _hotelFooterView.nameLabel.text;
        }
        [params setObject:username forKey:@"username"];
        NSString *usermobile =  _travelFooterView.phoneLabel.text;
        if (_hotelFooterView) {
            usermobile = _hotelFooterView.phoneLabel.text;
        }
        [params setObject:usermobile forKey:@"usermobile"];
        NSInteger goods_type;
        switch (self.result.type) {
            case TravelLineDetailType:{
                NSString *startTime =  _travelFooterView.startTimeBtn.titleLabel.text;
                [params setObject:startTime forKey:@"start_date"];
                goods_type = 3;
                break;
                }
            case TravelSpecialtyDetailType:{
                goods_type = 4;
                break;
            }
            case ScenicoDetailType:{
                NSString *startTime =  _travelFooterView.startTimeBtn.titleLabel.text;
                if (_hotelFooterView) {
                    startTime = self.result.checkInTime;
                }
                [params setObject:startTime forKey:@"start_date"];
                goods_type = 2;
                break;
            }
            default:
                break;
        }
        [params setObject:[NSNumber numberWithInteger:goods_type] forKey:@"goods_type"];
    }else{
        [params setObject:self.result.checkInDate forKey:@"start_date"];
        [params setObject:self.result.checkOutDate forKey:@"end_date"];
        [params setObject:self.result.roomType forKey:@"room_type"];
         NSInteger prenum =  _hotelFooterView.countLabel.text.integerValue;
        [params setObject:[NSNumber numberWithInteger:prenum] forKey:@"prenum"];
        NSString *username =  _hotelFooterView.nameLabel.text;
        NSString *usermobile =   _hotelFooterView.phoneLabel.text;
        [params setObject:username forKey:@"username"];
        [params setObject:usermobile forKey:@"usermobile"];
        [params setObject:[NSNumber numberWithInteger:1] forKey:@"goods_type"];
        [params setObject:[NSNumber numberWithInteger:self.result.roomId] forKey:@"room_id"];
        NSString *stayName =  _hotelFooterView.comeinNameLabel.text;
        [params setObject:stayName forKey:@"stayman"];
        [params setObject:@(self.result.totalNight) forKey:@"totalNight"];
    }
    
    [DialogUtils showLoding];
    [MineDataTool saveOrderInfo:params success:^(OrderEditRes *result) {
        [DialogUtils hideLoding];
        if(result.isSucc){
            //提交订单成功
            [self tapPay:result];
        }else{
             [DialogUtils showTips:result.msg];
        }
    } failure:^(NSError *error) {
        [DialogUtils hideLoding];
        [DialogUtils showTips:@"提交订单失败"];
    }];
}

-(void)tapPay:(OrderEditRes *)result{
    NSLog(@"-------tapPay");
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    IPNPreSignMessageUtil *preSign=[[IPNPreSignMessageUtil alloc]init];
    preSign.appId=kNowPayAppId;
    preSign.mhtOrderNo=result.datas.order_sn;
    preSign.mhtOrderName=result.datas.goods_name;
    preSign.mhtOrderType=@"01";
    preSign.mhtCurrencyType=@"156";
    preSign.mhtOrderAmt=[NSString stringWithFormat:@"%.0f",result.datas.totalprice *100];
    preSign.mhtOrderDetail=@"订单详情";
    preSign.mhtOrderStartTime=[dateFormatter stringFromDate:[NSDate date]];
    NSString *norifyUrl = [NSString  stringWithFormat:@"%@%@",BASE_URL,@"notify/appnoticeupdate.jspx"];
    preSign.notifyUrl= norifyUrl;
    preSign.mhtCharset=@"UTF-8";
    preSign.mhtOrderTimeOut=@"3600";
    preSign.mhtReserved=@"test";
    
    NSString *originStr =  [preSign generatePresignMessage];
    _presignStr = originStr;
    NSString *outputStr = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)originStr,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    NSLog(@"%@",outputStr);
    //开始准备网络请求
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    [params setObject:kAppValue forKey:kAppkey];
    [params setObject:outputStr forKey:@"paydata"];
    
    NSString *url = [NSString stringWithFormat:@"%@order/order_sign.json",BASE_URL];
    // 1.获得请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    [self showAlertWait];
    // 2.发送请求
    [mgr GET:url parameters:params
     success:^(AFHTTPRequestOperation *operation, id responseObj) {
         [self hideAlert];
         NSString *result =  [[NSString alloc]initWithData:responseObj encoding:NSUTF8StringEncoding];
         if(result){
             NSLog(@"success:%@",result);
             NSString* payData=[_presignStr stringByAppendingString:@"&"];
             payData=[payData stringByAppendingString:result];
             NSLog(@"%@",payData);
             [IpaynowPluginApi pay:payData AndScheme:@"IpaynowPluginTraveling" viewController:self delegate:self];
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [self hideAlert];
         [self showAlertMessage:kErrorNet];
         NSLog ( @"failure:%@" , error );
     }];
}

-(void)IpaynowPluginResult:(NSString*)result{
    NSMutableString *resultString = [[NSMutableString alloc] initWithString:kResult];
    [resultString appendString:result];
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:kNote
                                                    message:resultString
                                                   delegate:nil
                                          cancelButtonTitle:kConfirm
                                          otherButtonTitles:nil];
    [alert show];
}
- (void)showAlertMessage:(NSString*)msg
{
    mAlert = [[UIAlertView alloc] initWithTitle:kNote message:msg delegate:nil cancelButtonTitle:kConfirm otherButtonTitles:nil, nil];
    [mAlert show];
}
- (void)showAlertWait {
    mAlert = [[UIAlertView alloc] initWithTitle:kWaiting message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [mAlert show];
    UIActivityIndicatorView* aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    aiv.center = CGPointMake(mAlert.frame.size.width / 2.0f - 15, mAlert.frame.size.height / 2.0f + 10 );
    [aiv startAnimating];
    [mAlert addSubview:aiv];
}

- (void)hideAlert {
    if (mAlert != nil)
    {
        [mAlert dismissWithClickedButtonIndex:0 animated:YES];
        mAlert = nil;
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}


-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
